class ReqList {
  constructor() {
    if (ReqList.instance) {
      return ReqList.instance;
    }
    ReqList.instance = this;

    this.queue = [];
    this.isProcessing = false;
  }

  // 添加请求到队列
  push(fn) {
    return new Promise((resolve, reject) => {
      this.queue.push({
        fn,
        resolve,
        reject,
      });
      this.processQueue();
    });
  }

  // 处理队列
  async processQueue() {
    if (this.isProcessing || this.queue.length === 0) {
      return;
    }

    this.isProcessing = true;
    const { fn, resolve, reject } = this.queue.shift();

    try {
      const result = await fn();
      resolve(result);
    } catch (error) {
      reject(error);
    } finally {
      this.isProcessing = false;
      this.processQueue();
    }
  }
}

export default ReqList;
